package cn.tedu.kcircle.content.front.adapter.http;

import cn.tedu.kcircle.category.front.api.rpc.CategoryFrontRpcApi;
import cn.tedu.kcircle.category.front.api.rpc.po.CategoryStandardPO;
import cn.tedu.kcircle.check.admin.api.rpc.CheckAdminRpcApi;
import cn.tedu.kcircle.comment.front.api.rpc.CommentFrontRpcApi;
import cn.tedu.kcircle.common.dto.ResourceDTO;
import cn.tedu.kcircle.common.exception.BusinessException;
import cn.tedu.kcircle.common.po.CurrentPrincipal;
import cn.tedu.kcircle.common.po.PageData;
import cn.tedu.kcircle.common.restful.ResponseCode;
import cn.tedu.kcircle.content.front.adapter.converter.ContentConverter;
import cn.tedu.kcircle.content.front.repository.model.ContentAddModel;
import cn.tedu.kcircle.content.front.repository.model.ContentStandardModel;
import cn.tedu.kcircle.content.front.repository.persist.ContentRepository;
import cn.tedu.kcircle.content.front.service.ContentFrontService;
import cn.tedu.kcircle.content.front.service.bo.ContentAddBO;
import cn.tedu.kcircle.content.front.service.bo.ContentListItemBO;
import cn.tedu.kcircle.content.front.service.bo.ContentStandardBO;
import cn.tedu.kcircle.detail.api.rpc.DetailRpcApi;
import cn.tedu.kcircle.detail.protocol.dto.DetailAddDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@AllArgsConstructor
public class ContentFrontServiceImpl implements ContentFrontService {
    //    @Value("${kcircle.dao.default-query-page-size}")
//    private Integer defaultQueryPageSize;
    private CategoryFrontRpcApi categoryFrontRpcApi;
    private ContentRepository contentRepository;
    private DetailRpcApi detailRpcApi;
    private CheckAdminRpcApi checkAdminRpcApi;
    private CommentFrontRpcApi commentFrontRpcApi;
    private ContentConverter converter;

    /*发布文章*/
    private void addNew(ContentAddBO contentAddBO, Integer resourceType) {
        System.out.println("开始处理【发布文章】的业务，当事人id：{}" + contentAddBO.getAuthorId());

        Long categoryId = contentAddBO.getCategoryId();
        CategoryStandardPO category = categoryFrontRpcApi.getCategoryById(categoryId);
        System.out.println("categoryId:" + categoryId + "category:" + category);
        if (category == null) {
            String message = "发布文章失败，选择的类别不存在！";
            log.warn(message);
            throw new BusinessException(ResponseCode.ERROR_NOT_FOUND, message);
        }

        if (category.getEnable() != 1) {
            String message = "发布文章失败，选择的类别已经被禁用！";
            log.warn(message);
            throw new BusinessException(ResponseCode.ERROR_CONFLICT, message);
        }

        ContentAddModel contentAddModel = converter.bo2Model(contentAddBO);
        Long contentId = contentRepository.insert(contentAddModel);

        DetailAddDTO detailAddDTO = new DetailAddDTO();
        detailAddDTO.setResourceId(contentId);
        detailAddDTO.setResourceType(resourceType);
        detailAddDTO.setDetail(contentAddModel.getDetail());
        detailRpcApi.saveDetail(detailAddDTO);
    }

    @Override
    public void addQuestion(ContentAddBO contentAddBO) {
        addNew(contentAddBO, RESOURCE_TYPE_QUESTION);
    }

    @Override
    public void addArticle(ContentAddBO contentAddBO) {
        addNew(contentAddBO, RESOURCE_TYPE_ARTICLE);
    }

    @Override
    public void addVideo(ContentAddBO contentAddBO) {
        addNew(contentAddBO, RESOURCE_TYPE_VIDEO);
    }

    @Override
    public void addAnswer(ContentAddBO contentAddBO) {
        addNew(contentAddBO, RESOURCE_TYPE_ANSWER);
    }

    @Override
    public void addIdea(ContentAddBO contentAddBO) {
        addNew(contentAddBO, RESOURCE_TYPE_IDEA);
    }


    /*删除文章*/
    @Override
    public void deleteById(Long id) {
        log.debug("开始处理【根据ID删除文章】的业务，参数：{}", id);
        ContentStandardModel standardById = contentRepository.getStandardById(id);
        if (standardById == null) {
            String message = "删除文章失败，尝试删除的文章数据不存在！";
            log.warn(message);
            throw new BusinessException(ResponseCode.ERROR_NOT_FOUND, message);
        }

        int rows = contentRepository.deleteById(id);
        if (rows != 1) {
            String message = "删除文章失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new BusinessException(ResponseCode.ERROR_CONFLICT, message);
        }

        //TODO 改为异步消息
        ResourceDTO resourceDTO = new ResourceDTO();
        Integer resourceType = contentRepository.getResourceTypeById(id);
        resourceDTO.setResourceType(resourceType);
        resourceDTO.setResourceId(id);
        checkAdminRpcApi.deleteCheckLogByResource(resourceDTO);

        //TODO 改为异步消息

        commentFrontRpcApi.deleteByResource(resourceDTO);
    }

    @Override
    public void passCheck(CurrentPrincipal currentPrincipal, Long id, String remarks) {

    }

    @Override
    public void rejectCheck(CurrentPrincipal currentPrincipal, Long id, String remarks) {

    }

    @Override
    public ContentStandardBO getStandardById(Long id) {
        return null;
    }

    @Override
    public PageData<ContentListItemBO> list(Integer pageNum) {
        return null;
    }

    @Override
    public List<Object> getUserActivities(CurrentPrincipal currentPrincipal) {
        return null;
    }

//    /*根据ID查询文章*/
//    @Override
//    public ContentStandardVO getStandardById(Long id) {
//        log.debug("开始处理【根据ID查询文章】的业务，参数：{}", id);
//        ContentStandardVO queryResult=contentRepository.getStandardById(id);
//        if (queryResult == null) {
//            String message = "查询文章详情失败，文章数据不存在！";
//            log.warn(message);
//            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
//        }
//        return queryResult;
//    }


//    @Override
//    public PageData<ContentListltemVO> list(Integer pageNum) {
//        log.debug("开始处理【查询文章列表】的业务，页码：{}", pageNum);
//        return contentRepository.list(pageNum, defaultQueryPageSize);
//    }
//
//    @Override
//    public List<Object> getUserActivities(CurrentPrincipal currentPrincipal) {
//        Long authorId=currentPrincipal.getUserId();
//        List<Object> activities = new ArrayList<>();
//        commentRepository.listByResourceAuthorId(authorId);
//        List<ContentStandardVO> content=contentRepository.listByAuthorId(authorId);
//        activities.addAll(comment);
//        activities.addAll(content);
//
//        List<Object> sortedActivities = activities.stream()
//                .sorted((o1, o2) -> {
//                    LocalDateTime d1 = null;
//                    LocalDateTime d2 = null;
//
//                    if (o1 instanceof CommentListItemVO vo1) {
//                        d1 = vo1.getGmtModified();
//                    } else if (o1 instanceof ContentStandardVO vo2) {
//                        d1 = vo2.getGmtModified();
//                    }
//
//                    if (o2 instanceof CommentListItemVO vo3) {
//                        d2 = vo3.getGmtModified();
//                    } else if (o2 instanceof ContentStandardVO vo4) {
//                        d2 = vo4.getGmtModified();
//                    }
//
//                    if (d1 != null && d2 != null) {
//                        return d2.compareTo(d1); // 倒序排序
//                    }
//                    return 0;
//                })
//                .collect(Collectors.toList());
//            return sortedActivities;
//    }
//
//    private void updateCheckById(CurrentPrincipal currentPrincipal, Long id, Integer checkState, String remarks){
//        ContentStandardVO content=contentRepository.getStandardById(id);
//        if (content==null){
//            String message = "将文章的审核状态修改为【" + CHECK_STATE_TEXT[checkState] + "】失败，文章数据不存在！";
//            log.warn(message);
//            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
//        }
//
//        if (content.getCheckState().equals(checkState)){
//            String message="将文章的审核状态修改为【" + CHECK_STATE_TEXT[checkState] + "】失败，此文章已经处于" + CHECK_STATE_TEXT[checkState] + "状态！";
//            log.warn(message);
//            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
//        }
//
//        Content updateContent=new Content();
//        updateContent.setId(id);
//        updateContent.setCheckState(checkState);
//        int rows=contentRepository.updateById(updateContent);
//        if (rows!=1){
//            String message = "将文章的审核状态修改为【" + CHECK_STATE_TEXT[checkState] + "】失败，服务器忙，请稍后再尝试！";
//            log.warn(message);
//            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
//        }
//
//        CheckLog checkLog=new CheckLog();
//        checkLog.setCheckUserId(currentPrincipal.getUserId());
//        checkLog.setCheckUserName(currentPrincipal.getUsername());
//        checkLog.setResourceId(RESOURCE_TYPE_ARTICLE);
//        checkLog.setResourceBrief(content.getBrief());
//        checkLog.setFromCheckState(content.getCheckState());
//        checkLog.setToCheckState(checkState);
//        checkLog.setTypeId(content.getTypeId());
//        checkLog.setRemarks(remarks);
//        checkLog.setGmtModified(LocalDateTime.now());
//        rows = checkLogRepository.insert(checkLog);
//        if (rows != 1) {
//            String message = "将文章的审核状态修改为【" + CHECK_STATE_TEXT[checkState] + "】失败，服务器忙，请稍后再尝试！";
//            log.warn(message);
//            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
//        }


}




